from google.appengine.ext import webapp, gql
from google.appengine.ext.webapp.util import run_wsgi_app
from models import Business, Deal, Comment, CheckIn, User
from test.test_typechecks import Integer
import util
import string
import logging
import Consts

##
#this file main role is to handle with likes feature

class DataBaseLikeSetHandler(webapp.RequestHandler):

    def get(self): 
        self.response.out.write(''' 
        <html> 
          <body> 
            <form method="post"> 
              <p>User_name: <input type="integer" name="user_name" /></p>
              <p>Email: <input type="integer" name="email" /></p>
              <p>Deal_type: <input type="integer" name="deal_type" /></p>
              <p><input type="submit" /></p>  
            </form> 
          </body> 
        </html> 
        ''')
        
    def post(self):
        logging.info("Start like set request")
        
        self.response.headers['Content-Type'] = 'text/xml'
        
        #get the xml
        email = self.request.get("email", "")
        user_name = self.request.get("user_name", "")
        deal_type =  self.request.get("deal_type", "")
        
        logging.debug("email = " + unicode(email) + ", user_name = " + unicode(user_name) +", deal_type = " + unicode(deal_type))
        user = None
        if (email != ""):
            #just to be sure user is exist
            user_list = User.all()
            user_list.filter("email ==",email)
            user = user_list.get()
            if (user == None):
                #create new user
                user = User()
                user.credit = 5
                user.user_name = user_name
                user.email = email
                user.likes = ""
                user.likes_int = ""
        
        if (int(deal_type) < len(Consts.DEAL_TYPES_ALL)):
            like = Consts.DEAL_TYPES_ALL[int(deal_type)-1][1][0].capitalize()
            like_int = Consts.DEAL_TYPES_ALL[int(deal_type)-1][0]
        else:
            like = Consts.DEFAULT_DEAL_TYPES[int(deal_type)-len(Consts.DEAL_TYPES_ALL)][1][0].capitalize()
            like_int = Consts.DEFAULT_DEAL_TYPES[int(deal_type)-len(Consts.DEAL_TYPES_ALL)][0]
            if (like == "Rest"):
                like="Restaurant"
        
       
        #check if like already exists
        if (not (like in user.likes)):
            if (user.likes != ""):
                user.likes = user.likes + "#" + like
                user.likes_int = user.likes_int + "#" + like_int 
            else:
                user.likes = like
                user.likes = like_int
                
        user.save()
        logging.debug("likes = " + unicode(user.likes))
        logging.info("finish check in set request: success")

class DataBaseLikeFacebookSetHandler(webapp.RequestHandler):

    def get(self): 
        self.response.out.write(''' 
        <html> 
          <body> 
            <form method="post"> 
              <p>User_name: <input type="integer" name="user_name" /></p>
              <p>Email: <input type="integer" name="email" /></p>
              <p>Deal_type: <input type="integer" name="deal_type" /></p>
              <p><input type="submit" /></p>  
            </form> 
          </body> 
        </html> 
        ''')
        
    def post(self):
        logging.info("Start like facebook set request")
        
        self.response.headers['Content-Type'] = 'text/xml'
        
        #get the xml
        email = self.request.get("email", "")
        user_name = self.request.get("user_name", "")
        data_str =  self.request.get("data_str", "")
        
        logging.debug("email = " + unicode(email) + ", user_name = " + unicode(user_name) +", data_str = " + unicode(data_str))
        user = None
        if (email != ""):
            #just to be sure user is exist
            user_list = User.all()
            user_list.filter("email ==",email)
            user = user_list.get()
            if (user == None):
                #create new user
                user = User()
                user.credit = 5
                user.user_name = user_name
                user.email = email
                user.likes = ""
                user.likes_int = ""
        else:
            logging.debug("finish facebook set: failed")
            return
                
        data_str_lst = data_str.split("#")
        for data_str_elem in data_str_lst:
            like = ""
            like_int = ""
            for data_type in Consts.DEAL_TYPES_ALL:
                data_type_int = data_type[0]
                data_type_name = data_type[1][0]
                data_type_hints = data_type[1]
                logging.debug("data_type name = " + data_type_name + " data_type_hints = " + unicode(data_type_hints) + ", data_type_int = " + unicode(data_type_int))
            
                #search for hints
                for hint in data_type_hints:
                    if (data_str_elem != None and data_str_elem.lower().find(hint) != -1):
                        logging.debug("found deal_type = " + data_type_name)
                        like  = data_type_name.capitalize()
                        like_int = data_type_int
                        break
                if (like != ""):
                    if (like == "rest"):
                        like="restaurant"
                    break         
            
                #check if like already exists
            if (not (like in user.likes)):
                if (user.likes != ""):
                    user.likes = user.likes + "#" + like
                    user.likes_int = user.likes_int + "#" + like_int 
                else:
                    user.likes = like
                    user.likes_int = like_int
        
        user.save()
        logging.debug("likes = " + unicode(user.likes))
        logging.info("finish check in facebook set request: success")
        
        
        
        
class DataBaseLikesGetHandler(webapp.RequestHandler):

    def get(self): 
        self.response.out.write(''' 
        <html> 
          <body> 
            <form method="post"> 
              <p>Email: <input type="integer" name="email" /></p>
              <p><input type="submit" /></p>  
            </form> 
          </body> 
        </html> 
        ''')
        
    def post(self):
        logging.info("Start likes get request")
        
        self.response.headers['Content-Type'] = 'text/xml'
        
        #get the business_key
        email = self.request.get("email", "")
        user_name = self.request.get("user_name", "")
        
        logging.info("email = " + unicode(email) + ", user_name = " + unicode(user_name))
        
        xml_result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        xml_result += "<root>\n"
        
        if (email != ""):
            #just to be sure user is exist
            user_list = User.all()
            user_list.filter("email ==",email)
            user = user_list.get()
            if (user == None):
                #create new user
                user = User()
                user.credit = 5
                user.user_name = user_name
                user.email = email
                user.likes = ""    
                user.put()
            xml_result += user.to_xml()
        else:
            logging.debug("finish likes get request: failed")    
            return
        
        xml_result += "</root>\n"
        
        logging.debug("xml response:")
        logging.debug(xml_result)
        self.response.out.write(xml_result)
        logging.info("Finish likes request")
        

    
application = webapp.WSGIApplication([('/likes/set', DataBaseLikeSetHandler),
                                      ('/likes/facebook_set', DataBaseLikeFacebookSetHandler),
                                      ('/likes/get', DataBaseLikesGetHandler)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()        